<?php
/**
 * Author:   tangxiaowen
 * Email:    846506584@qq.com
 * Date:     2021/3/3 0003 14:56
 * Describe: 企业微信服务 - 授权相关类
 */

namespace app\common\server\corp;

use think\exception\ValidateException;

class Auth extends Base
{
    /**
     * @var string 获取预授权码url
     */
    private $getPreAuthCodeUrl = 'https://qyapi.weixin.qq.com/cgi-bin/service/get_pre_auth_code?suite_access_token=%s';

    /**
     * @var string 设置授权配置url
     */
    private $setAuthConfigUrl = 'https://qyapi.weixin.qq.com/cgi-bin/service/set_session_info?suite_access_token=%s';

    /**
     * @var string 获取授权链接url
     */
    private $getAuthUrl = 'https://open.work.weixin.qq.com/3rdapp/install?suite_id=%s&pre_auth_code=%s&redirect_uri=%s&state=%s';

    /**
     * @var string 获取永久授权码url
     */
    private $getPermanentByCodeUrl = 'https://qyapi.weixin.qq.com/cgi-bin/service/get_permanent_code?suite_access_token=%s';

    /**
     * 获取预授权码
     * @throws ValidateException
     * @return string
     */
    public function getPreAuthCode(): string
    {
        $res = $this->curlFn(sprintf($this->getPreAuthCodeUrl, (new Token())->getSuiteAccessToken()));
        return $this->setResponse($res)['pre_auth_code']?? '';
    }

    /**
     * 设置授权配置
     * @param string $preAuthCode 预授权码
     * @throws ValidateException
     */
    public function setAuthConfig(string $preAuthCode): void
    {
        $res = $this->curlFn(sprintf($this->setAuthConfigUrl, (new Token())->getSuiteAccessToken()), [
            'pre_auth_code' => $preAuthCode,
            'session_info' => [
                'auth_type' => 1, //授权类型：0 正式授权， 1 测试授权。 默认值为0。注意，请确保应用在正式发布后的授权类型为“正式授权”
            ]
        ], true);
        $this->setResponse($res);
    }

    /**
     * 获取授权链接
     * @param int $adminId 操作人ID
     * @throws ValidateException
     * @return string
     */
    public function getAuthUrl(int $adminId): string
    {
        $preAuthCode = $this->getPreAuthCode();
        $this->setAuthConfig($preAuthCode);
        return sprintf($this->getAuthUrl, $this->suiteId, $preAuthCode, urlencode($this->redirectUriInstall), $adminId);
    }

    /**
     * 获取永久授权码
     * -通过授权码获取企业永久授权信息并入库
     * @param string $authCode 临时授权码
     * @param int $adminId 操作人ID
     * @throws ValidateException
     * @return
     */
    public function getPermanentByCode(string $authCode, $adminId = ''): void
    {
        $res = $this->curlFn(sprintf($this->getPermanentByCodeUrl, (new Token())->getSuiteAccessToken()), [
            'auth_code' => $authCode
        ]);
        $temp = $this->setResponse($res);
        trace(11111);
        trace($temp);
        $autoCorpTemp = [
            'access_token'             => $temp['access_token'],
            'access_token_expires_in'  => $temp['expires_in'],
            'permanent_code'           => $temp['permanent_code'],
            'corpid'                   => $temp['auth_corp_info']['corpid'],
            'corp_name'                => $temp['auth_corp_info']['corp_name'],
            'corp_type'                => $temp['auth_corp_info']['corp_type'],
            'corp_round_logo_url'      => $temp['auth_corp_info']['corp_round_logo_url'],
            'corp_square_logo_url'     => $temp['auth_corp_info']['corp_square_logo_url'],
            'corp_user_max'            => $temp['auth_corp_info']['corp_user_max'],
            'corp_agent_max'           => $temp['auth_corp_info']['corp_agent_max'],
            'corp_wxqrcode'            => $temp['auth_corp_info']['corp_wxqrcode'],
            'corp_full_name'           => $temp['auth_corp_info']['corp_full_name'],
            'subject_type'             => $temp['auth_corp_info']['subject_type'],
            'verified_end_time'        => $temp['auth_corp_info']['verified_end_time']?? '',
            'corp_scale'               => $temp['auth_corp_info']['corp_scale'],
            'corp_industry'            => $temp['auth_corp_info']['corp_industry'],
            'corp_sub_industry'        => $temp['auth_corp_info']['corp_sub_industry'],
            'location'                 => $temp['auth_corp_info']['location'],
            'auth_info'                => json_encode($temp['auth_info'], JSON_UNESCAPED_UNICODE),
            'auth_user_info'           => json_encode($temp['auth_user_info'], JSON_UNESCAPED_UNICODE),
            'auth_code'                => $authCode,
            'create_user_id'           => $adminId,
            'auth_status'              => 2
        ];

        $corpId = db('wechat_corp')->where('corpid', $autoCorpTemp['corpid'])->value('id');
        if($corpId){
            $autoCorpTemp['update_time'] = time();
            $res = db('wechat_corp')->where('id', $corpId)->update($autoCorpTemp);
        }else{
            $autoCorpTemp['create_time'] = time();
            $res = db('wechat_corp')->insert($autoCorpTemp);
        }
        if(!$res){
            exception('授权回调写入企业微信失败');
        }
    }

}